package com.leyou.item.controller;

import com.leyou.common.pojo.PageResult;
import com.leyou.item.service.GoodsService;
import com.leyou.bo.SpuBo;
import com.leyou.pojo.Sku;
import com.leyou.pojo.SpuDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author XiaoLuo
 * @ClassName: GoodsController
 * @Description: ${todo}
 * @date 2019/4/18 15:29
 * 这里把SPU  SKU合并 所以不能用RequestMapping
 */
@RestController public class GoodsController {

	@Autowired private GoodsService goodsServiceImpl;

	/**
	 * 根据页面传入的查询条件分页查询spu商品列表
	 *
	 * @param key
	 * @param saleable
	 * @param page
	 * @param rows
	 * @return
	 */
	@GetMapping("spu/page") public ResponseEntity<PageResult<SpuBo>> querySpuByPage(
			@RequestParam(value = "key", required = false) String key,
			@RequestParam(value = "saleable", required = false) Boolean saleable,
			@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "rows", defaultValue = "5") Integer rows) {
		PageResult<SpuBo> result = this.goodsServiceImpl
				.querySpuByPage(key, saleable, page, rows);
		if (result != null && result.getItems() != null
				&& result.getItems().size() != 0) {
			return ResponseEntity.ok(result);
		}
		return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
	}

	/**
	 * 新增商品
	 *
	 * @param spuBo
	 * @return
	 */
	@PostMapping("goods") public ResponseEntity<Void> saveGoods(
			@RequestBody SpuBo spuBo) {
		try {
			this.goodsServiceImpl.save(spuBo);
			return ResponseEntity.status(HttpStatus.CREATED).build();
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
					.build();
		}
	}

	/**
	 * 修改商品栏时
	 * 根据spuid回显的商品spudetail属性
	 *
	 * @param spuId
	 * @return
	 */
	@GetMapping("spu/detail/{spuId}") public ResponseEntity<SpuDetail> querySpuDetailById(
			@PathVariable("spuId") Long spuId) {
		SpuDetail spuDetail = this.goodsServiceImpl.querySpuDetailById(spuId);
		if (spuDetail != null) {
			return ResponseEntity.ok(spuDetail);
		}
		return ResponseEntity.status(HttpStatus.NO_CONTENT).build();

	}

	/**
	 * 修改商品烂时
	 * 根据supid回显商品sku属性
	 *
	 * @param spuId
	 * @return
	 */
	@GetMapping("sku/list") public ResponseEntity<List<Sku>> querySkuBySpuId(
			@RequestParam("id") Long spuId) {
		List<Sku> skus = this.goodsServiceImpl.querySkuBySpuId(spuId);
		if (skus != null && 0 != skus.size()) {
			return ResponseEntity.ok(skus);
		}
		return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
	}

	/**
	 * 保存修改的商品信息
	 * @param spuBo
	 * @return
	 */
	@PutMapping("goods") public ResponseEntity<Void> updateGoods(
			@RequestBody SpuBo spuBo) {

			this.goodsServiceImpl.update(spuBo);
			return ResponseEntity.status(HttpStatus.CREATED).build();

	}
}
